#include "util.h"

namespace libco {

static auto s_start_time = std::chrono::high_resolution_clock::now();

pid_t GetThreadId() {
    return syscall(SYS_gettid);
}

uint64_t GetCoroutineId() {
    return Coroutine::GetCoroutineId();
}

std::string GetCoroutineRole() {
    return Coroutine::GetCoroutineRole();
}

double GetElapsedMs() {
    // struct timespec ts = {0};
    // clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
    // return ts.tv_sec * 1000 + ts.tv_nsec / 1000000.0;
    auto end_time = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - s_start_time);
    return duration.count();
}

double GetElapsedUs() {
    auto end_time = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - s_start_time);
    return duration.count() > 1719247568005 ? 0 : duration.count();
}

double GetElapsedNs() {
    auto end_time = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - s_start_time);
    return duration.count();
}

std::string GetThreadName() {
    char thread_name[16] = {0};
    pthread_getname_np(pthread_self(), thread_name, 16);
    return std::string(thread_name);
}

void SetThreadName(const std::string &name) {
    pthread_setname_np(pthread_self(), name.substr(0, 15).c_str());
}

uint64_t GetCurrentTimeMs() {
    auto now = std::chrono::system_clock::now();
    auto duration = now.time_since_epoch();
    auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
    return static_cast<uint64_t>(millis);
}

std::string GetCurrentTimeStr() {
    auto now = std::chrono::system_clock::now();
    // 转换为time_t，time_t是自1970年1月1日以来的秒数
    std::time_t now_time_t = std::chrono::system_clock::to_time_t(now);
    // 使用localtime转换为本地时间
    std::tm* ptm = std::localtime(&now_time_t);

    std::stringstream ss;
    ss << std::put_time(ptm, "%Y-%m-%d %H:%M:%S");
    return ss.str();
}

}